package cn.tony.game.super_tank;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import cn.tony.game.super_tank.msg.Message;
import cn.tony.game.super_tank.msg.Messages;

public class GameClient {

    public static String ip   = "127.0.0.1";

    public static int    port = 8888;
    public String        name = "江东小霸王";

    public Game          game = new Game();

    public static void main(String[] args) throws Exception {
        new GameClient().start();

    }

    public void start() throws UnknownHostException, IOException {

        SettingFame sf = new SettingFame(this);

        sf.show1(true);

        // conn(game);
    }

    public void conn() throws UnknownHostException, IOException {
        Socket s = new Socket(ip, port);

        game.socket = s;
        game.start();
        // game.addself(false);

        OutputStream os = s.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);

        dos.writeUTF(name);
        dos.flush();

        DataInputStream dis = new DataInputStream(s.getInputStream());

        game.id = dis.readInt();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Messages msg = new Messages();
                    try {
                        Message message = msg.relove(dis);
                        if (message == null) {
                            continue;
                        }
                        message.reslove(dis);
                        message.doSomething(game);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
